import 'dart:io';

import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'package:im_flutter_sdk/im_flutter_sdk.dart';
import 'package:provider/provider.dart';
import 'package:qunaimedical/components/unread_count_view.dart';
import 'package:qunaimedical/init/provider.dart';
import 'package:qunaimedical/pages/conversations/conversations_page.dart';
import 'package:qunaimedical/pages/me.dart';
import 'package:qunaimedical/pages/moment/moment_home.dart';
import 'package:qunaimedical/pages/summary.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/log_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/values/constants.dart';

class HomePage extends StatefulWidget {
  static const String routeName = '/home';

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with WidgetsBindingObserver
    implements EMChatManagerListener {
  String tag = '_HomePageState';

  int _tabIndex = 0;
  final _pageController = PageController();
  List<String> _tabImages = [
    'assets/images/ic_tab_home.png',
    'assets/images/ic_tab_quan.png',
    'assets/images/ic_tab_chat.png',
    'assets/images/ic_tab_me.png',
  ];
  List<String> _tabTitles = ['首页', '群爱圈', '消息', '我的'];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _initIM();
    // 添加收消息监听
    EMClient.getInstance.chatManager.addListener(this);
    // 获取IM未读消息数
    CommonUtils.getUnreadMsgCount(context);
    // 初始化微信配置
    initWX();
  }

  void initWX() async {
    if (Platform.isAndroid) {
      await registerWxApi(appId: Constants.wechatAppID, doOnAndroid: true);
    }
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.inactive:
        break;
      case AppLifecycleState.resumed:
        Log.d(tag, 'AppLifecycleState.resumed:');
        // 在程序回到前台时，检查IM连接状态。
        _initIM();
        break;
      case AppLifecycleState.paused:
        break;
      case AppLifecycleState.detached:
        break;
    }
  }

  void _initIM() async {
    try {
      var user = SPUtils.getUser();
      var status = EMClient.getInstance.isLoginBefore;
      Log.i('IM status: $status');
      if (user != null && !status) {
        await EMClient.getInstance.login(user.username, '000000');
      }
    } on EMError catch (e) {
      Log.i(e);
    }
  }

  @override
  void dispose() {
    super.dispose();
    _pageController.dispose();
    // 移除收消息监听
    EMClient.getInstance.chatManager.removeListener(this);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView(
        physics: NeverScrollableScrollPhysics(),
        children: [
          SummaryPage(),
          MomentHome(),
          ConversationPage(),
          MePage(),
        ],
        controller: _pageController,
        onPageChanged: (index) {
          setState(() {
            _tabIndex = index;
          });
        },
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: List.generate(
          _tabImages.length,
          (index) {
            Widget unreadMsgCountView = Positioned(
              top: 0.0,
              right: 0.0,
              child: Offstage(
                offstage: index != 1,
                child: UnreadCountView(
                    count: context.watch<StoreInfo>().unreadMsgCount),
              ),
            );
            EdgeInsetsGeometry _padding =
                EdgeInsets.only(left: 10, right: 10, top: 7, bottom: 3);
            return BottomNavigationBarItem(
              icon: Stack(
                children: [
                  Container(
                    padding: _padding,
                    child: Image.asset(
                      _tabImages[index],
                      width: 30,
                      color: _tabIndex == index
                          ? Theme.of(context).primaryColor
                          : null,
                    ),
                  ),
                  unreadMsgCountView,
                ],
              ),
              label: _tabTitles[index],
            );
          },
        ),
        currentIndex: _tabIndex,
        onTap: (index) {
          _pageController.jumpToPage(index);
        },
        selectedItemColor: Colors.black87,
        type: BottomNavigationBarType.fixed,
        selectedFontSize: 14,
        unselectedFontSize: 14,
      ),
    );
  }

  @override
  onCmdMessagesReceived(List<EMMessage> messages) {}

  @override
  onConversationRead(String from, String to) {}

  @override
  onConversationsUpdate() {}

  @override
  onMessagesDelivered(List<EMMessage> messages) {}

  @override
  onMessagesRead(List<EMMessage> messages) {}

  @override
  onMessagesRecalled(List<EMMessage> messages) {}

  @override
  onMessagesReceived(List<EMMessage> messages) {
    CommonUtils.getUnreadMsgCount(context);
  }
}
